package com.shenhaofeng.rxcache.source;

import com.shenhaofeng.rxcache.utils.StreamHelper;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;

/**
 * Created by haofeng on 2016/9/25.
 */

public class SerializableSource<T extends Serializable> extends DiskSource<T> {


    private File mCacheDir;


    public SerializableSource(File mCacheDir) {
        this.mCacheDir = mCacheDir;
    }

    @Override
    boolean saveDataToDisk(String key, T data) {
        if (!mCacheDir.exists() || !mCacheDir.isDirectory()) {
            return false;
        }
        try {
            StreamHelper.write(new File(mCacheDir, key), data);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    T readDataFromDisk(String key) {
        if (!mCacheDir.exists() || !mCacheDir.isDirectory()) {
            return null;
        }
        try {
            return (T) StreamHelper.read(new File(mCacheDir, key));
        } catch (IOException | ClassNotFoundException | ClassCastException e) {
            e.printStackTrace();
            return null;
        }
    }
}
